{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "Chapter 08\n",
    "# 使用递归方法生成阶乘\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "def factorial(n):\n",
    "    # 基本情况：当n等于0或1时，阶乘为1\n",
    "    if n == 0 or n == 1:\n",
    "        return 1\n",
    "    # 递归情况：计算n的阶乘等于n乘以(n-1)的阶乘\n",
    "    else:\n",
    "        return n * factorial(n - 1)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T16:23:46.347592Z",
     "end_time": "2024-07-03T16:23:46.351975Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0! = 1\n",
      "1! = 1\n",
      "2! = 2\n",
      "3! = 6\n",
      "4! = 24\n",
      "5! = 120\n",
      "6! = 720\n",
      "7! = 5040\n",
      "8! = 40320\n",
      "9! = 362880\n"
     ]
    }
   ],
   "source": [
    "# 测试阶乘函数\n",
    "for i in range(10):\n",
    "    print(f'{i}! = {factorial(i)}')"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T16:23:53.441315Z",
     "end_time": "2024-07-03T16:23:53.459342Z"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
